package com.pai4j.message.template;

import com.pai4j.message.core.template.AbstractTemplateEngine;
import com.pai4j.message.factory.TemplateEngineFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 简单模板引擎
 * 使用 ${variable} 格式的简单变量替换
 *
 * @author PAI4J Team
 * @date 2025-11-01
 */
@Slf4j
@Component
public class SimpleTemplateEngine extends AbstractTemplateEngine {

    private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\$\\{([^}]+)}");

    @PostConstruct
    public void register() {
        TemplateEngineFactory.register(this);
        log.info("SimpleTemplateEngine已注册");
    }

    @Override
    public String getName() {
        return "simple";
    }

    @Override
    protected String doRender(String template, Map<String, Object> context) {
        if (template == null || template.isEmpty()) {
            return "";
        }

        if (context == null || context.isEmpty()) {
            return template;
        }

        StringBuffer result = new StringBuffer();
        Matcher matcher = VARIABLE_PATTERN.matcher(template);

        while (matcher.find()) {
            String varName = matcher.group(1);
            Object varValue = context.get(varName);
            String replacement = varValue != null ? String.valueOf(varValue) : "";
            matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));
        }
        matcher.appendTail(result);

        return result.toString();
    }

    @Override
    public int getPriority() {
        return 100; // 默认优先级（最低）
    }
}

